"""
gRPC响应工厂类

提供统一的接口来创建gRPC响应实例，根据返回码枚举生成对应的响应对象
"""

from typing import Any

# 导入返回码基类和枚举
from src.constants.return_codes import BaseCodeEnum, ReturnCode
# 导入gRPC消息定义
from . import audio_service_pb2


class ResponseFactory:
    """
    gRPC响应工厂类
    
    提供静态方法来创建各种类型的gRPC响应实例，
    根据返回码枚举自动生成包含正确code和msg的响应对象
    """

    @staticmethod
    def create_tts_response(
            code: BaseCodeEnum,
            audio_data: bytes = b'',
            request_id: str = "",
            **kwargs
    ) -> audio_service_pb2.TTSResponse:
        """
        创建TTS响应实例
        
        Args:
            code: 返回码枚举实例
            audio_data: 音频数据
            request_id: 请求ID
            **kwargs: 其他额外参数
            
        Returns:
            audio_service_pb2.TTSResponse: TTS响应实例
        """
        # 创建TTS响应对象
        response = audio_service_pb2.TTSResponse()
        # 设置状态码
        response.code = code.code
        # 设置音频数据
        response.audio_data = audio_data
        # 设置请求ID
        response.request_id = request_id
        # 设置错误消息
        response.msg = code.message
        return response

    @staticmethod
    def create_stt_response(
            code: BaseCodeEnum,
            text: str = "",
            request_id: str = "",
            audio_file: str = "",
            language: str = "",
            detected_language: str = "unknown",
            **kwargs
    ) -> audio_service_pb2.STTResponse:
        """
        创建STT响应实例
        
        Args:
            code: 返回码枚举实例
            text: 转换后的文本
            request_id: 请求ID
            custom_message: 自定义消息（可选，会覆盖枚举中的消息）
            audio_file: 音频文件路径
            language: 语言设置
            detected_language: 检测到的语言
            **kwargs: 其他额外参数
            
        Returns:
            audio_service_pb2.STTResponse: STT响应实例
        """
        # 创建STT响应对象
        response = audio_service_pb2.STTResponse()
        # 设置状态码
        response.code = code.code
        # 设置请求ID
        response.request_id = request_id
        # 设置识别文本
        response.text = text
        # 设置错误消息
        response.msg = code.message

        # 如果提供了详细信息，构建STTResult
        if audio_file or language or detected_language != "unknown":
            # 创建STT结果对象
            stt_result = audio_service_pb2.STTResult()
            # 设置音频文件路径
            stt_result.audio_file = audio_file
            # 设置语言设置
            stt_result.language = language
            # 设置检测到的语言
            stt_result.detected_language = detected_language
            # 将结果复制到响应中
            response.result.CopyFrom(stt_result)

        return response

    @staticmethod
    def create_voiceprint_response(
            code: BaseCodeEnum,
            voiceprint_id: str = "",
            request_id: str = "",
            **kwargs
    ) -> audio_service_pb2.VoiceprintResponse:
        """
        创建声纹识别响应实例
        
        Args:
            code: 返回码枚举实例
            voiceprint_id: 声纹ID
            request_id: 请求ID
            custom_message: 自定义消息（可选，会覆盖枚举中的消息）
            **kwargs: 其他额外参数
            
        Returns:
            audio_service_pb2.VoiceprintResponse: 声纹识别响应实例
        """
        # 创建声纹识别响应对象
        response = audio_service_pb2.VoiceprintResponse()
        # 设置状态码
        response.code = code.code
        # 设置声纹ID
        response.voiceprint_id = voiceprint_id
        # 设置请求ID
        response.request_id = request_id
        # 设置错误消息
        response.msg = code.message
        return response

    @staticmethod
    def create_success_response(
            response_type: str,
            request_id: str = "",
            **kwargs
    ) -> Any:
        """
        创建成功响应实例的快捷方法
        
        Args:
            response_type: 响应类型 ('tts', 'stt', 'voiceprint')
            request_id: 请求ID
            **kwargs: 其他参数
            
        Returns:
            对应类型的成功响应实例
        """
        # 根据响应类型创建对应的成功响应
        if response_type.lower() == 'tts':
            return ResponseFactory.create_tts_response(
                ReturnCode.SUCCESS, request_id=request_id, **kwargs
            )
        elif response_type.lower() == 'stt':
            return ResponseFactory.create_stt_response(
                ReturnCode.SUCCESS, request_id=request_id, **kwargs
            )
        elif response_type.lower() == 'voiceprint':
            return ResponseFactory.create_voiceprint_response(
                ReturnCode.SUCCESS, request_id=request_id, **kwargs
            )
        else:
            raise ValueError(f"不支持的响应类型: {response_type}")

    @staticmethod
    def create_error_response(
            response_type: str,
            code: BaseCodeEnum,
            request_id: str = "",
            **kwargs
    ) -> Any:
        """
        创建错误响应实例的快捷方法
        
        Args:
            response_type: 响应类型 ('tts', 'stt', 'voiceprint')
            code: 错误码枚举实例
            request_id: 请求ID
            custom_message: 自定义错误消息
            **kwargs: 其他参数
            
        Returns:
            对应类型的错误响应实例
        """
        # 根据响应类型创建对应的错误响应
        if response_type.lower() == 'tts':
            return ResponseFactory.create_tts_response(
                code, request_id=request_id, **kwargs
            )
        elif response_type.lower() == 'stt':
            return ResponseFactory.create_stt_response(
                code, request_id=request_id, **kwargs
            )
        elif response_type.lower() == 'voiceprint':
            return ResponseFactory.create_voiceprint_response(
                code, request_id=request_id, **kwargs
            )
        else:
            raise ValueError(f"不支持的响应类型: {response_type}")
